<template>
  <view class="content">
    <view class="gradient-bg">
      <!-- 渐变背景 -->
      <view class="list-card-wrap">
        <view class="flex-row-between" style="margin-bottom: 8rpx;">
          <view class="flex-row">
            <text class="white-text font-24">单据编号</text>
            <text class="white-text font-24" style="margin-left: 20rpx;">{{ taskInfo.bizNo }}</text>
          </view>
        </view>
        <view class="list-card">
          <view class="">
            <text class="black-text-34">{{ taskInfo.supplierName }}</text>
          </view>
          <view class="content-blue flex-row">
            <view class="flex-column flex1">
              <text class="gray-text">到货总数</text>
              <text class="black-text">{{ taskInfo.totalQty }}</text>
            </view>
            <view class="split"></view>
            <view class="flex-column flex1">
              <text class="gray-text">收货总数</text>
              <text class="black-text">{{ taskInfo.checkTotalQty || 0 }}</text>
            </view>
          </view>
        </view>
      </view>
      <view class="s-input-wrap">
        <view class="s-input-box flex-row-between">
          <text class="gray-text font-30">托盘号</text>
          <input auto-focus="true" v-model="trayNo" class="s-input flex1" placeholder="请输入或扫描托盘号" />
          <image v-if="trayNo" class="s-input-icon clear-icon" src="/static/images/clear.png" @click="trayNo = ''">
          </image>
          <image class="s-input-icon" src="/static/images/scan.png"></image>
        </view>
      </view>
      <view class="s-input-wrap">
        <view class="s-input-box flex-row-between">
          <text class="gray-text font-30">物料编号</text>
          <!-- <picker v-if="productData.length" @change="(arr)=>bindPickerProduct(arr)" :value="product.productNo"
            :range="productData" range-key="productName">
            <view class="black-text font-34">{{product.productNo?product.productNo:'请选择物料'}}</view>
          </picker> -->
          <!-- <image class="s-input-icon" src="/static/images/scan.png"></image> -->
          <input v-model="productNo" @confirm="handleScan" class="s-input flex1" placeholder="请输入或扫描物料编号" />
          <image v-if="productNo" class="s-input-icon clear-icon" src="/static/images/clear.png" @click="clearField">
          </image>
          <image class="s-input-icon" src="/static/images/scan.png"></image>

        </view>
        <view class="s-input-box flex-row-between">
          <text class="gray-text font-30">物料名称</text>
          <text class="black-text font-30">{{ product.productName }}</text>
        </view>
        <view class="s-input-box flex-row-between">
          <text class="gray-text font-30">需求数量</text>
          <text class="black-text font-30">{{ product.arrivalQty }}</text>
        </view>
        <view class="s-input-box flex-row-between">
          <text class="gray-text font-30">已收数量</text>
          <text class="black-text font-30">{{ product.quantityReceived }}</text>
        </view>
        <view class="s-input-box flex-row">
          <text class="gray-text font-30">收货数量</text>
          <input @input="setNum" type="number" v-model="product.resultQty" class="s-input flex1" placeholder="请输入收货数量" />
          <text class="gray-text font-30">{{ productObj.cgUnitName }}</text>
        </view>
        <view class="s-input-box flex-row-between">
          <text class="gray-text font-30">生产日期</text>
          <picker mode="date" :value="productDate" @change="bindProductDateChange">
            <view class="black-text font-30">{{ productDate ? productDate : '请选择生产日期' }}</view>
          </picker>
          <!--<text class="black-text font-30">{{product.productDate}}</text>-->
        </view>
        <view class="s-input-box flex-row-between">
          <text class="gray-text font-30">有效期至</text>
          <text class="gray-text font-30">{{ productObj.qualityGuaranteePeriodTemp }}</text>

          <!-- <picker mode="date" :value="validDate" @change="bindValidDateChange">
            <view class="black-text font-30">{{validDate?validDate:'请选择有效期'}}</view>
          </picker> -->
          <!--<text class="black-text font-30">{{product.validDate}}</text>-->
        </view>
        <!-- <view class="s-input-box flex-row-between">
          <text class="gray-text font-30">批次号</text>
          <input v-model="product.batchNo" class="s-input flex1" placeholder="请输入批次号" />
        </view> -->
      </view>

      <view @click="addDetail" class="botton p-botton font-30"
        style="height: 92rpx; line-height:92rpx;margin: 0 25rpx;">
        收货
      </view>
    </view>

    <view class="table-wrap" style="padding-bottom: 100rpx;">
      <view class="flex-row-start" style="margin: 10rpx 0;">
        <text class="gray-text font-24">收货纪录</text>
        <uni-icons type="top" size="14" style="color: #8997A8;"></uni-icons>
      </view>
      <zb-table @dele="deleteDetail" :show-header="true" :columns="detailColumns" :fit="true" :border="true"
        :data="detailData">
      </zb-table>
    </view>

    <view class="content-list-total flex-row-between">
      <text class="gray-text">合计:</text>
      <view class="flex-row">
        <text class="gray-text">共<text class="blue-text font-38">{{ taskInfo.checkTotalQty || 0 }}</text>件</text>
        <view @click="completeTask" class="botton p-botton">完成</view>
      </view>
    </view>

  </view>
</template>

<script>
import {
  validNum,
  addDaysToDate,
  validateTrayCode
} from "@/utils/common"
import {
  getTaskInfoById,
  getBillReceiveDetailList,
  getBillProductList,
  addReceiveDetail,
  delByReceiveDetail,
  complete,
  saveBarcode,
  getTaskInfoByCode
} from "./api"


export default {
  onLoad(option) {
    this.taskId = option.id;
  },
  created() {
    this.tableHeiht = this.windowHeight - 420;
    this.getTaskDetail();
  },
  data() {
    return {
      productObj: {},
      productNo: "",
      tableHeiht: 0,
      date: '',
      warehouse: '',
      taskId: '',
      taskInfo: {},
      code: '',
      number: 12,
      detailData: [],
      productData: [],
      // selectStartDate:false,
      // selectEndDate:false,
      product: {},
      trayNo: '',
      productDate: '',
      validDate: '',
      detailColumns: [{
        type: 'index',
        label: '序号',
        align: 'center',
        width: 40
      },
      {
        name: 'trayNo',
        label: '托盘号',
        fixed: false,
        emptyString: '--'
      },
      {
        name: 'productNo',
        label: '物料编号',
        fixed: false,
        emptyString: '--'
      },
      {
        name: 'batchNo',
        label: '批次号',
        fixed: false,
        emptyString: '--'
      },
      {
        name: 'productName',
        label: '物料',
        sorter: false,
      },
      {
        name: 'qty',
        label: '数量'
      },
      {
        name: 'productionDate',
        label: '生产日期'
      },
      {
        name: 'expiryDate',
        label: '有效日期'
      },
      {
        name: 'operation',
        type: 'operation',
        label: '操作',
        renders: [{
          name: '/static/images/delete.png',
          type: 'icon',
          func: "dele",
          style: "width:24rpx;height:28rpx"
        },],
      },
      ],

    }
  },
  computed: {

  },
  methods: {
    clearField() {
      this.productNo = ''
      this.clearMaterialInfo()
    },
    clearMaterialInfo() {
      this.productObj = ''
      this.product = ''
      this.productDate = ''
    },
    handleScan() {
      getTaskInfoByCode(this.productNo).then(res => {
        if (res.code == 200) {
			this.pTipName = res.data.productName
			  this.clearMaterialInfo()
			  this.productObj = res.data
			  this.bindPickerProductTwo(this.productObj.productNo)
        }else{
			this.$modal.confirmClose(`商品『${this.pTipName}』不在订单${this.taskInfo.no}中`);
		}
      })
    },
    getArrivalQtyTxt(num) {
      try {
        if (!num || typeof num !== 'number') {
          return num;
        }

        const cgPsConver = Number(this.productObj?.cgPsConver);
        if (!cgPsConver) {
          return num;
        }

        const wholeUnits = Math.floor(num / cgPsConver);
        const remainder = num % cgPsConver;

        if (!this.productObj?.cgUnitName || (remainder > 0 && !this.productObj?.specUnitName)) {
          return num;
        }

        const mainUnit = wholeUnits + this.productObj.cgUnitName;
        return remainder > 0
          ? `${mainUnit}${remainder}${this.productObj.specUnitName}`
          : mainUnit;

      } catch (error) {
        console.warn('Error', error);
        return num;
      }
    },
    // 数量校验
    setNum(e) {
      this.$set(this.product, 'qty', validNum(e))
    },
    clearObjInfo(){
				this.productDate = '';
				this.productNo = '';
				this.product = {};
				this.productObj = {}
			},
    bindPickerProductTwo(no) {
      if (!this.productData || this.productData.length == 0) {
        return;
      }
     let o = this.productData.find(el => el.productNo == no)
				if(!o){
					this.clearObjInfo()
					// this.$modal.msg("此物料不在订单中");
					this.$modal.confirmClose(`商品『${this.pTipName}』不在订单${this.taskInfo.no}中`);
					return
				}
				this.product = o
				this.product.arrivalQty =   this.computedQtyTxt(this.product.qty)//   需求数量

				this.product.quantityReceived =  this.computedQtyTxt(this.getQuantityReceived());  //已收数量
				// this.product.qty = this.computedQtyTxt(this.product.qty - this.getQuantityReceived(),'noUni')  //收货数量
				// if(this.product.qty < 0){
				// 	this.product.qty = 0
				// }

    },
    computedQtyTxt(num,type){
				try {
					if (!this.productObj?.productNo || !this.productData?.length) {
						return 0;
					}
					const product = this.productData.find(el => el.productNo === this.productObj.productNo);

					if (!product?.qty) {
						return 0;
					}

					const cgPsConver = Number(this.productObj.cgPsConver) || 0;
					const ylPsConver = Number(this.productObj.ylPsConver) || 0;
					const conversionRate = cgPsConver * ylPsConver;

					if (!conversionRate) {
						return num;
					}

					let cn  = 0
					if(type =='noUni'){
						cn = Math.floor(num / conversionRate)
					}else{
						cn = Math.floor(num / conversionRate) + this.productObj.cgUnitName;
					}
					return cn
				} catch (error) {
					console.error('Error in computedQtyTxt:', error);
					return 0;
				}
			},
    bindProductDateChange(e) {
      this.productDate = e.detail.value
      this.product.batchNo = addDaysToDate(this.productDate, 0, 1)
      this.productObj.qualityGuaranteePeriodTemp = addDaysToDate(this.productDate, this.productObj.qualityGuaranteePeriod)
    },
    bindValidDateChange(e) {
      this.validDate = e.detail.value
    },
    getTaskDetail() {
      getTaskInfoById(this.taskId).then(res => {
        if (res.code == 200) {
          this.taskInfo = res.data
          console.log(this.taskInfo);
          // 继续查询收货任务明细
          getBillReceiveDetailList({
            billNo: this.taskInfo.bizNo,
            pageNum: 1,
            pageSize: 999
          }).then(res => {
            if (res.code == 200) {
              this.productData = res.rows;
            }
          })
          this.getBillProductList()
        }
      })
    },
    // 查询收货清单(物料列表)
    getBillProductList() {
      getBillProductList({
        billNo: this.taskInfo.bizNo,
        pageNum: 1,
        pageSize: 999
      }).then(res => {
        if (res.code == 200) {
          this.detailData = res.rows;
        }
      })
    },
    // bindProductDateChange: function(e) {
    // 	this.selectStartDate = true;
    // 	this.$set(this.product,'productDate',e.detail.value)
    // },
    // bindValidDateChange: function(e) {
    // 	this.selectEndDate = true;
    // 	this.$set(this.product,'validDate',e.detail.value)
    // },
    // 校验收货数量不能大于需求数量
    validQty() {
      let productNum = parseFloat(this.product.qty)
      this.detailData.forEach(item => {
        if (item.productNo == this.product.productNo) {
          productNum += parseFloat(item.qty)
        }
      })
      if (productNum > this.product.arrivalQty) {
        return false
      }
      return true
    },
    //获取已收数量
    getQuantityReceived() {
      let productNum = parseFloat(0)
      this.detailData.forEach(item => {
        if (item.productNo == this.product.productNo) {
          productNum += parseFloat(item.qty)
        }
      })
      return productNum
    },
    // 加入收货单
    addDetail() {
      if (!this.trayNo) {
        this.$modal.msg("请输入托盘号");
        return;
      }
      if (!this.product.productNo) {
        this.$modal.msg("请先选择物料");
        return;
      }
      if (!this.validQty()) {
        this.$modal.msg("物料收货数量大于需求数量");
        return;
      }
      if (!this.productDate) {
        this.$modal.msg("请选择生产日期");
        return;
      }
      let _qty =  this.productObj?.cgPsConver ?( Number(this.product.resultQty)*Number(this.productObj?.cgPsConver)*Number(this.productObj.ylPsConver)) : this.product.resultQty

      let obj = {
        bizNo: this.taskInfo.bizNo,
        trayNo: this.trayNo,
        productNo: this.product.productNo,
        productName: this.product.productName,
        productUnit: this.product.productUnit,
        qty: _qty,
        batchNo: this.product.batchNo,
        productDate: this.productDate,
        validDate: this.productObj.qualityGuaranteePeriodTemp
      }
      // if(this.selectStartDate){
      // 	obj.productDate = this.product.productDate;
      // }
      // if(this.selectEndDate){
      // 	obj.validDate = this.product.validDate;
      // }
      addReceiveDetail(obj).then(res => {
        if (res.code == 200) {
          this.clearMaterialInfo()
          this.$modal.msgSuccess("操作成功");
          let barcodeObj = {
            productNo: this.product.productNo,
            quantity: this.product.qty
          }
          this.getTaskDetail();
          /*
          // 需要保存条码后调用打印方法
          printModule.printLabelAsync({
            'barcode': res.data.barcode,
            'title': res.data.barcode + '\n\n物料编号：'+ this.product.productNo + '\n数量：'+this.product.qty,
            'distance': 500,
          },(ret) => {
            console.log(ret);
          });*/
          this.$set(this, 'product', {});
          // this.selectStartDate = false;
          // this.selectEndDate = false;
        }
      })
    },
    deleteDetail(row) {
      this.$modal.confirm('是否确认删除数据').then(() => {
        delByReceiveDetail(row).then(res => {
          if (res.code == 200) {
            this.$modal.msgSuccess("操作成功");
            this.getTaskDetail();
          }
        })
      })
    },
    completeTask() {
      let confimText = '是否确认完成？'
      if (this.taskInfo.checkTotalQty < this.taskInfo.totalQty) {
        confimText = '收货总数小于到货总数,是否确认完成？'
      }
      this.$modal.confirm(confimText).then(() => {
        complete({
          bizNo: this.taskInfo.bizNo
        }).then(res => {
          if (res.code == 200) {
            this.$modal.msgSuccess("操作成功");
            // this.getTaskDetail();
            // 延迟1秒跳转
            uni.$emit('refreshList', {
              msg: '页面更新'
            })
            setTimeout(() => {
              uni.navigateBack();
            }, 1000);
          }
        })
      })
    },
  }
}
</script>

<style>
page {
  background-color: #F8F8F8;
}
</style>
<style scoped></style>
